package com.example.ws.controller;

import cn.hutool.core.util.StrUtil;
import com.example.ws.mapper.UserMapper;
import com.example.ws.model.User;
import com.example.ws.service.IUserService;
import com.example.ws.vo.PageVo;
import com.example.ws.vo.RestResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * resful接口
 * @RestController是@Controller和@ResponseBody的结合
 *
 */
@RestController
@RequestMapping("/user")
//tags 里写接口说明
@Api(tags = "用户相关接口")
public class Usercontroller {
    /**
     * 自动注入IUserService接口，Spring会自动找到他的实现bean
     */
    @Autowired
    private IUserService userService;
    /**
     * 提供用户CRUD操作接口
     *
     * 返回信息：{
     *  状态码 status:0,
     *    错误信息 message;'',
     *    查询结果 data:{},
     * }
     * @RequestBody 接收请求体中的json数据，并转换为User对象
     * @RequestParam 接收URL中的参数
     *
     */
    //新增用户接口
    @PostMapping("/add")
    @ApiOperation("添加用户")
    public RestResultVo<String> add(@RequestBody User user){
         String add = userService.add(user);
         //StrUtil.isNotBlank()方法判断字符串是否不为空且不为空白字符
         if (StrUtil.isNotBlank(add)){
             return RestResultVo.ok(add);
         }
         return RestResultVo.failed("添加失败");
    }
    //修改用户接口
    @PostMapping("/edit")
    @ApiOperation("修改用户")
    public RestResultVo<User> edit(@RequestBody User user){
        User edit = userService.editByUserId(user);
        if (edit!=null){
            return RestResultVo.ok(edit);
        }
        return RestResultVo.failed();
    }
    //删除用户接口
    @GetMapping("/delete")
    @ApiOperation("删除用户")
    public RestResultVo<Integer> delete(String userId){
        int deleteOne = userService.delete(userId);
        return RestResultVo.ok(deleteOne);
    }
    //用户详情接口
    @GetMapping("/detail")
    @ApiOperation("用户详情")
    public RestResultVo<User> detail(String userId){
        User user = userService.detail(userId);
        return RestResultVo.ok(user);
    }
    //分页查询接口
    @GetMapping("/page")
    @ApiOperation("分页查询")
    public RestResultVo<PageVo<User>> page(String userName,Integer pageNumber,Integer pageSize){
       PageVo<User> page = userService.page(userName,pageNumber,pageSize);
       return RestResultVo.ok(page);
    }
    @PostMapping("/login")
    @ApiOperation("登录")
    public RestResultVo<User> login(@RequestParam String name,@RequestParam String password){
        if (name == null && password == null) {
            throw new RuntimeException("用户密码为空！");
        }
        User log = userService.login(name,password);
        if (log !=null){
            return RestResultVo.ok(log);
        }
        return RestResultVo.failed();
    }
}
